package com.zhongshengnetwork.rightbe.game.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.CircularProgressButton;
import com.google.gson.JsonObject;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.HandlerDefine;
import com.zhongshengnetwork.rightbe.common.activity.BaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.NetworkBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.game.model.PKAnswerModel;
import com.zhongshengnetwork.rightbe.game.model.PKMessage;
import com.zhongshengnetwork.rightbe.game.view.CircleTextProgressbar;
import com.zhongshengnetwork.rightbe.game.view.VerticalProgressBar;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKAModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKMsgModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKResultModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKResultUserInfo;
import com.zhongshengnetwork.rightbe.gsonmodel.PKRoomModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKRuleModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKSubjectModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKUserModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.my.activity.SettingsActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

public class PKActivity extends NetworkBaseActivity {
    private String data;
    private PKRoomModel pkRoomModel;
    private PKRuleModel pkRuleModel;
    private PKUserModel pkUserModel = null;
    private PKUserModel anotherPKUserModel;
    private PKUserModel roleUserModel;
    private List<PKSubjectModel> subjectList = null;
    private List<PKAModel> pkaList = null;
    private PKAnswerModel pkAnswerModel = null;
    private PKAModel weakpkaModel = null;
    private PKMsgModel pkMsgModel;
    private PKResultModel pkResultModel;
    private PKResultUserInfo acceptPKResultUserInfo;
    private PKResultUserInfo sendPKResultUserInfo;

    private CountDownTime mTime;
    private boolean isTimeOut = false;
    private int oldTime = 0;
    public MyHandler myHandler;

    private CircleTextProgressbar progressBar;
    private CircularProgressButton pk_progress_bg;
    private VerticalProgressBar pk_left_score_progress;
    private VerticalProgressBar pk_right_score_progress;
    private TextView pk_left_score;
    private TextView pk_right_score;

    private CircularProgressButton pk_left_window_bg;
    private CircularProgressButton pk_left_window_circle;
    private ImageView pk_left_window_header;
    private TextView pk_left_window_nickname;

    private CircularProgressButton pk_right_window_bg;
    private CircularProgressButton pk_right_window_circle;
    private ImageView pk_right_window_header;
    private TextView pk_right_window_nickname;

    private TextView pk_title;
    private TextView pk_first_select_answer;
    private TextView pk_second_select_answer;
    private TextView pk_third_select_answer;
    private TextView pk_fourth_select_answer;
    private View pk_first_select_answer_bg;
    private View pk_second_select_answer_bg;
    private View pk_third_select_answer_bg;
    private View pk_fourth_select_answer_bg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pk);

        //注册广播
        registerBoradcastReceiver();
        myHandler = new MyHandler();
        Intent intent = this.getIntent();
        data = intent.getStringExtra("data");
        pkUserModel = (PKUserModel) intent.getSerializableExtra("pkuser");
        pkRoomModel = (PKRoomModel) intent.getSerializableExtra("pkroom");
        pkRuleModel = (PKRuleModel) intent.getSerializableExtra("pkrule");
        roleUserModel = (PKUserModel) intent.getSerializableExtra("roleuser");
        anotherPKUserModel = (PKUserModel) intent.getSerializableExtra("anotherpkuser");
        subjectList = GsonTools.getPKSubjectModel(data);
        if (anotherPKUserModel == null){
            pkaList = GsonTools.getPKAModel(data);
        }else {

        }
        pkAnswerModel = new PKAnswerModel();
        pkAnswerModel.answerArray = new ArrayList<>();
        pkAnswerModel.answerArray.add("A");
        pkAnswerModel.answerArray.add("B");
        pkAnswerModel.answerArray.add("C");
        pkAnswerModel.answerArray.add("D");
        pkAnswerModel.scoreArray = CommonUtils.stringToArrayList(pkRuleModel.getPkanswerscore());

        pkMsgModel = new PKMsgModel();
        if (anotherPKUserModel != null){
            pkMsgModel.setTargetId(anotherPKUserModel.getUserid());
            pkMsgModel.setRoomID(pkRoomModel.getId());
        }

        //以下是UI
        pk_progress_bg = (CircularProgressButton)findViewById(R.id.pk_progress_bg);
        pk_progress_bg.setBackgroundColor(Color.TRANSPARENT);
        pk_progress_bg.setStrokeColor(getResources().getColor(R.color.mainColor));

        progressBar = (CircleTextProgressbar)findViewById(R.id.pk_progress);
        // 和系统普通进度条一样，0-100。
        progressBar.setProgressType(CircleTextProgressbar.ProgressType.COUNT);
// 改变进度条。
        progressBar.setProgressLineWidth(20);// 进度条宽度。
// 改变进度条颜色。
        progressBar.setProgressColor(Color.parseColor("#48CFAD"));
// 改变外部边框颜色。
        progressBar.setOutLineColor(Color.WHITE);
// 改变圆心颜色。
        progressBar.setInCircleColor(Color.TRANSPARENT);
        progressBar.setProgress(0);

        CircleTextProgressbar.OnCountdownProgressListener progressListener = new CircleTextProgressbar.OnCountdownProgressListener() {
            @Override
            public void onProgress(int what, int progress) {
                if (what == 1) {
                    int time = pkRuleModel.getPkanswertime()-(int)(0.01*progress*pkRuleModel.getPkanswertime());
                    if (oldTime != time){
                        oldTime = time;
                        progressBar.setText(time+"");
                        answerTime(time);
                        pkAnswerModel.setAnswerTime(time);
                    }

                }
                // 比如在首页，这里可以判断进度，进度到了100或者0的时候，你可以做跳过操作。
            }
        };
        // 监听进度。
        progressBar.setCountdownProgressListener(1, progressListener);

        pk_left_score_progress = (VerticalProgressBar) findViewById(R.id.pk_left_score_progress);
        pk_left_score_progress.setProgress(0);
        pk_right_score_progress = (VerticalProgressBar) findViewById(R.id.pk_right_score_progress);
        pk_right_score_progress.setProgress(0);
        pk_left_score = (TextView) findViewById(R.id.pk_left_score);
        pk_right_score = (TextView) findViewById(R.id.pk_right_score);


        pk_left_window_bg = (CircularProgressButton) findViewById(R.id.pk_left_window_bg);
        pk_left_window_bg.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        pk_left_window_bg.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        pk_left_window_circle = (CircularProgressButton) findViewById(R.id.pk_left_window_circle);
        pk_left_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_left_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_left_window_header = (ImageView) findViewById(R.id.pk_left_window_header);
        Glide.with(PKActivity.this).load(pkUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PKActivity.this)).dontAnimate().into(pk_left_window_header);
        pk_left_window_nickname = (TextView) findViewById(R.id.pk_left_window_nickname);
        pk_left_window_nickname.setText(pkUserModel.getNickname());

        pk_right_window_bg = (CircularProgressButton) findViewById(R.id.pk_right_window_bg);
        pk_right_window_bg.setBackgroundColor(getResources().getColor(R.color.wordBgColor));
        pk_right_window_bg.setStrokeColor(getResources().getColor(R.color.wordBgColor));
        pk_right_window_circle = (CircularProgressButton) findViewById(R.id.pk_right_window_circle);
        pk_right_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_right_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_right_window_header = (ImageView) findViewById(R.id.pk_right_window_header);
        pk_right_window_nickname = (TextView) findViewById(R.id.pk_right_window_nickname);
        if (anotherPKUserModel == null){
            Glide.with(PKActivity.this).load(roleUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PKActivity.this)).dontAnimate().into(pk_right_window_header);
            pk_right_window_nickname.setText(roleUserModel.getNickname());
        }else {
            Glide.with(PKActivity.this).load(anotherPKUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PKActivity.this)).dontAnimate().into(pk_right_window_header);
            pk_right_window_nickname.setText(anotherPKUserModel.getNickname());
        }

        pk_title = (TextView) findViewById(R.id.pk_title);
        pk_first_select_answer = (TextView) findViewById(R.id.pk_first_select_answer);
        pk_second_select_answer = (TextView)findViewById(R.id.pk_second_select_answer);
        pk_third_select_answer = (TextView)findViewById(R.id.pk_third_select_answer);
        pk_fourth_select_answer = (TextView)findViewById(R.id.pk_fourth_select_answer);
        pk_first_select_answer_bg = (View) findViewById(R.id.pk_first_select_answer_bg);
        pk_second_select_answer_bg = (View)findViewById(R.id.pk_second_select_answer_bg);
        pk_third_select_answer_bg = (View)findViewById(R.id.pk_third_select_answer_bg);
        pk_fourth_select_answer_bg = (View)findViewById(R.id.pk_fourth_select_answer_bg);
        updateData();

    }

    public void startAnswerTime(){
        progressBar.setText(pkRuleModel.getPkanswertime()+"");
        // 设置倒计时时间毫秒，默认3000毫秒。
        progressBar.setTimeMillis(pkRuleModel.getPkanswertime()*1000);
// 如果需要自动倒计时，就会自动走进度。
        progressBar.reStart();
    }

    public void onClickBack(View view){
        back("亲，对战进行中，强制退出将扣除金币哦~","1",true);
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("按下了back键   onKeyDown()");
            back("亲，对战进行中，强制退出将扣除金币哦~","1",true);
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    /**
     * 第一种方法 使用android封装好的 CountDownTimer
     * 创建一个类继承 CountDownTimer
     */
    class CountDownTime extends CountDownTimer {

        //构造函数  第一个参数代表总的计时时长  第二个参数代表计时间隔  单位都是毫秒
        public CountDownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) { //每计时一次回调一次该方法
            //guess_word_level.setText("倒计时:"+l/1000+"秒");
            if (pkAnswerModel.isAnswerTimeOut() == true){
                if (pkAnswerModel.getAnswerTimeOut() > 0){
                    pkAnswerModel.setAnswerTimeOut(pkAnswerModel.getAnswerTimeOut()-1);
                }
            }
        }

        @Override
        public void onFinish() { //计时结束回调该方法
            isTimeOut = true;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (pkAnswerModel.isAnswerTimeOut() == true){
                        back("亲，对方结束了答题哦~","0",false);
                    }
                }
            });
        }
    }

    private void startTime(){
        if (pkRoomModel == null){
            return;
        }
        if (mTime != null){
            mTime.cancel();
            mTime = null;
        }
        isTimeOut = false;
        mTime = new CountDownTime((long)(pkRuleModel.getPkwaittimeOut()*1000), (long)1000);//初始化对象
        mTime.start();
    }

    private void stopTime(){
        if (pkRoomModel == null){
            return;
        }
        if (mTime != null){
            mTime.cancel();
            mTime = null;
        }
    }

    class MyHandler extends Handler {
        //默认构造函数
        public MyHandler(){
            super();
        }

        //带有Looper参数的构造函数
        public MyHandler(Looper L){
            super(L);
        }

        //子类重写次方法，处理消息

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg == null || msg.obj == null){
                return;
            }
            PKMsgModel pkMsgModel = GsonTools.getPKMsgModel(CommonUtils.formatString(pkAnswerModel.getContent()));
            if (msg.obj.toString().equals(HandlerDefine.pkquitmsg)){
                back(pkMsgModel.getContent(),"0",false);
            }else if (msg.obj.toString().equals(HandlerDefine.pkanswermsg)){
                answer(pkMsgModel.getAnswer(),pkMsgModel.getTime());
            }else if (msg.obj.toString().equals(HandlerDefine.pkresultmsg)){
                stopTime();
                pkResultModel = new PKResultModel();
                pkResultModel.setAddgoldcountaccept(pkMsgModel.getAddgoldcountaccept());
                pkResultModel.setAddgoldcountsend(pkMsgModel.getAddgoldcountsend());
                pkResultModel.setAddplaylevelaccept(pkMsgModel.getAddplaylevelaccept());
                pkResultModel.setAddplaylevelsend(pkMsgModel.getAddplaylevelsend());

                acceptPKResultUserInfo = new PKResultUserInfo();
                acceptPKResultUserInfo.setHistoryWinlinkcount(0);
                acceptPKResultUserInfo.setLosePkcount(0);
                acceptPKResultUserInfo.setPkcount(0);
                acceptPKResultUserInfo.setUserid(pkMsgModel.getAcceptuserid());
                acceptPKResultUserInfo.setWinLinkcount(pkMsgModel.getAcceptwinlinkcount());
                acceptPKResultUserInfo.setWinPkcount(0);

                sendPKResultUserInfo = new PKResultUserInfo();
                sendPKResultUserInfo.setHistoryWinlinkcount(0);
                sendPKResultUserInfo.setLosePkcount(0);
                sendPKResultUserInfo.setPkcount(0);
                sendPKResultUserInfo.setUserid(pkMsgModel.getSenduserid());
                sendPKResultUserInfo.setWinLinkcount(pkMsgModel.getSendwinlinkcount());
                sendPKResultUserInfo.setWinPkcount(0);

                Intent intent = new Intent(PKActivity.this, EndPKActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("pkuser",pkUserModel);
                bundle.putSerializable("pkanswer", pkAnswerModel);//序列化
                if (anotherPKUserModel == null){
                    bundle.putSerializable("roleuser",roleUserModel);
                }else {
                    bundle.putSerializable("anotherpkuser",anotherPKUserModel);
                }
                bundle.putSerializable("pkresult",pkResultModel);
                bundle.putSerializable("acceptpkresultuserinfo",acceptPKResultUserInfo);
                bundle.putSerializable("sendpkresultuserinfo",sendPKResultUserInfo);
                intent.putExtras(bundle);//发送数据
                startActivity(intent);
                progressBar.stop();
                finish();

            }
        }
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.print("onReceive接收到广播了" + "\n");
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.PKMsg)){
                String content = intent.getStringExtra(APIKey.contentKey);
                PKMsgModel pkMsgModel = GsonTools.getPKMsgModel(content);
                pkAnswerModel.setContent(content);
                if (pkMsgModel.getName().equals(PKMsgModel.PKAnswer)){
                    Message msg = new Message();
                    msg.obj = new String(HandlerDefine.pkanswermsg);
                    myHandler.sendMessage(msg);
                }else if (pkMsgModel.getName().equals(PKMsgModel.PKQuit)){
                    Message msg = new Message();
                    msg.obj = new String(HandlerDefine.pkquitmsg);
                    myHandler.sendMessage(msg);
                }else if (pkMsgModel.getName().equals(PKMsgModel.PKResult)){
                    Message msg = new Message();
                    msg.obj = new String(HandlerDefine.pkresultmsg);
                    myHandler.sendMessage(msg);
                }

            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.PKMsg);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    //以下是对战处理逻辑
    private void back(String msg, final String type, boolean isCancle){
        stopTime();
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(PKActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(msg);
        builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                progressBar.stop();
                dialog.dismiss();
                leaveRoom(type);
                finish();
            }
        });
        if (isCancle == true){
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
        dialog = builder.create();
        dialog.show();
    }

    public void onClickSelect(View view){
        if (pkAnswerModel.isCanClick() == true){
            if (pkAnswerModel.getMySubjectIndex() >= subjectList.size()){
                //我的题目回答完毕了
                return;
            }
            int time = pkAnswerModel.getAnswerTime();
            int selectTag = 0;
            switch (view.getId()){
                case R.id.pk_first_select_answer:
                    selectTag = 0;
                    break;
                case R.id.pk_second_select_answer:
                    selectTag = 1;
                    break;
                case R.id.pk_third_select_answer:
                    selectTag = 2;
                    break;
                case R.id.pk_fourth_select_answer:
                    selectTag = 3;
                    break;
            }
            int score = getScore(time,pkAnswerModel.getMySubjectIndex());
            pkAnswerModel.setCanClick(false);
            pkAnswerModel.setMySelectIndex(selectTag);
            String answer = pkAnswerModel.answerArray.get(selectTag);
            PKSubjectModel pkSubjectModel = subjectList.get(pkAnswerModel.getMySubjectIndex());
            int tag = pkAnswerModel.answerArray.indexOf(pkSubjectModel.getAnswer());
            if (selectTag == tag){
                updateAnswerSelect(tag,1,true);
                pkAnswerModel.setMyScore(pkAnswerModel.getMyScore()+score);
                pkAnswerModel.setMyLinkCorrectCount(pkAnswerModel.getMyLinkCorrectCount()+1);
                updateScoreProgress(true);
                if (pkAnswerModel.getMyLinkCorrectCount() > pkAnswerModel.getMyMaxLinkCorrectCount()){
                    pkAnswerModel.setMyMaxLinkCorrectCount(pkAnswerModel.getMyLinkCorrectCount());
                }
            }else {
                if (pkAnswerModel.getMyLinkCorrectCount() > pkAnswerModel.getMyMaxLinkCorrectCount()){
                    pkAnswerModel.setMyMaxLinkCorrectCount(pkAnswerModel.getMyLinkCorrectCount());
                }
                pkAnswerModel.setMyLinkCorrectCount(0);
                updateAnswerSelect(selectTag,2,true);
            }
            pkAnswerModel.setMySubjectIndex(pkAnswerModel.getSubjectIndex());
            if (anotherPKUserModel != null){
                pkMsgModel.setName(PKMsgModel.PKAnswer);
                pkMsgModel.setAnswer(answer);
                pkMsgModel.setTime(time);
                sendPKMsg();
            }

            showCorrectAnswer();

        }
        //updateAnswerSelect(int index, int type, boolean isMy)
        Log.e("TAG","onClickSelect");
    }

    private void updateData(){
        Log.e("TAG","更新题目1");
        if (pkAnswerModel.getSubjectIndex() >= subjectList.size()){//答题完毕
            Log.e("TAG","上传结果");
            stopTime();
            //上传结果
            updatePKResult();
            return;
        }
        if (pkAnswerModel.getMySubjectIndex() != pkAnswerModel.getAnotherSubjectIndex()){
            return;
        }
        pk_first_select_answer.setBackgroundColor(Color.parseColor("#FFFFFF"));
        pk_second_select_answer.setBackgroundColor(Color.parseColor("#FFFFFF"));
        pk_third_select_answer.setBackgroundColor(Color.parseColor("#FFFFFF"));
        pk_fourth_select_answer.setBackgroundColor(Color.parseColor("#FFFFFF"));
        pk_first_select_answer_bg.setVisibility(View.VISIBLE);
        pk_second_select_answer_bg.setVisibility(View.VISIBLE);
        pk_third_select_answer_bg.setVisibility(View.INVISIBLE);
        pk_fourth_select_answer_bg.setVisibility(View.INVISIBLE);
        Log.e("TAG","更新题目2");
        pkAnswerModel.setAnswerTimeOut(false);
        PKSubjectModel pkSubjectModel = subjectList.get(pkAnswerModel.getSubjectIndex());
        String title = pkSubjectModel.getTitle();
        if (!CommonUtils.isEmpty(pkSubjectModel.getKindtype())){
            title = "【"+pkSubjectModel.getKindtype()+"】"+title;
        }
        pk_title.setText(title);
        pk_first_select_answer.setText(pkSubjectModel.getOne());
        pk_second_select_answer.setText(pkSubjectModel.getTwo());
        if (pkSubjectModel.getSelectCount() > 2){
            pk_third_select_answer.setText(pkSubjectModel.getThree());
            pk_third_select_answer.setVisibility(View.VISIBLE);
        }else {
            pk_third_select_answer.setVisibility(View.INVISIBLE);
        }
        if (pkSubjectModel.getSelectCount() > 3){
            pk_fourth_select_answer.setText(pkSubjectModel.getFour());
            pk_fourth_select_answer.setVisibility(View.VISIBLE);
        }else {
            pk_fourth_select_answer.setVisibility(View.INVISIBLE);
        }

        if (roleUserModel != null){
            weakpkaModel = pkaList.get(pkAnswerModel.getSubjectIndex());
        }
        int tag = pkAnswerModel.answerArray.indexOf(pkSubjectModel.getAnswer());
        int x = (int) (Math.random() * pkSubjectModel.getSelectCount());
        while (x == tag){
            x = (int) (Math.random() * pkSubjectModel.getSelectCount());
        }
        pkAnswerModel.setMySelectIndex(x);

        pkAnswerModel.setCanClick(true);
        pkAnswerModel.setNewSubject(true);
        pkAnswerModel.setSubjectIndex(pkAnswerModel.getSubjectIndex()+1);
        startAnswerTime();
    }

    //发送PK通知
    private void sendPKMsg(){

        JsonObject content = null;
        if (pkMsgModel.getName().equals(PKMsgModel.PKAnswer)){
            content = new JsonObject();
            content.addProperty("answer",pkMsgModel.getAnswer());
            content.addProperty("time",pkMsgModel.getTime()+"");
        }else if (pkMsgModel.getName().equals(PKMsgModel.PKQuit)){
            content = new JsonObject();
            content.addProperty(APIKey.typeKey,pkMsgModel.getType()+"");
            content.addProperty(APIKey.contentKey,pkMsgModel.getContent());
        }else if (pkMsgModel.getName().equals(PKMsgModel.PKResult)){
            content = new JsonObject();
            content.addProperty("senduserid",pkMsgModel.getSenduserid());
            content.addProperty("sendscore",pkMsgModel.getSendscore()+"");
            content.addProperty("sendwinlinkcount",pkMsgModel.getSendwinlinkcount()+"");
            content.addProperty("sendlinkcorrect",pkMsgModel.getSendlinkcorrect()+"");
            content.addProperty("addplaylevelsend",pkMsgModel.getAddplaylevelsend()+"");
            content.addProperty("addgoldcountsend",pkMsgModel.getAddgoldcountsend());

            content.addProperty("acceptuserid",pkMsgModel.getAcceptuserid());
            content.addProperty("acceptscore",pkMsgModel.getAcceptscore()+"");
            content.addProperty("acceptwinlinkcount",pkMsgModel.getAcceptwinlinkcount()+"");
            content.addProperty("acceptlinkcorrect",pkMsgModel.getAcceptlinkcorrect()+"");
            content.addProperty("addplaylevelaccept",pkMsgModel.getAddplaylevelaccept()+"");
            content.addProperty("addgoldcountaccept",pkMsgModel.getAddgoldcountaccept()+"");
        }

        if (content == null){
            return;
        }
        content.addProperty(APIKey.nameKey,pkMsgModel.getName());
        content.addProperty("roomID",pkMsgModel.getRoomID()+"");

        JsonObject userinfo = new JsonObject();
        userinfo.addProperty(APIKey.useridKey,CustomApplication.loginModel.getUid());
        userinfo.addProperty(APIKey.nameKey,CustomApplication.loginModel.getNickname());
        userinfo.addProperty(APIKey.portraituriKey,CustomApplication.loginModel.getThumbheader());
        PKMessage pkMessage = new PKMessage(content.toString(),userinfo.toString());
        final io.rong.imlib.model.Message message = io.rong.imlib.model.Message.obtain(pkMsgModel.getTargetId(), Conversation.ConversationType.PRIVATE, pkMessage);
        message.setSenderUserId(CustomApplication.loginModel.getUid());
        message.setSentStatus(io.rong.imlib.model.Message.SentStatus.SENDING);
        message.setMessageDirection(io.rong.imlib.model.Message.MessageDirection.SEND);
        String pushData = "";

        RongIMClient.getInstance().sendMessage(message, pushData, "", new RongIMClient.SendMessageCallback() {
            @Override
            public void onSuccess(Integer arg0) {
                message.setSentStatus(io.rong.imlib.model.Message.SentStatus.SENT);// 已发送
                RongIMClient.getInstance().getMessage(arg0, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
                    @Override
                    public void onSuccess(io.rong.imlib.model.Message message) {

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }

            @Override
            public void onError(Integer arg0, RongIMClient.ErrorCode arg1) {
                message.setSentStatus(io.rong.imlib.model.Message.SentStatus.FAILED);// 发送失败
                RongIMClient.getInstance().getMessage(arg0, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
                    @Override
                    public void onSuccess(io.rong.imlib.model.Message message) {

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }
        }, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
            @Override
            public void onSuccess(final io.rong.imlib.model.Message message) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {

            }
        });
    }

    //离开房间
    private void leaveRoom(String type){
        if (pkRoomModel != null){
            String url = "miniapp/pkappid/quitpk.do";
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put(APIKey.typeKey,type);
            map.put(APIKey.idKey,pkRoomModel.getId()+"");
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onError(String msg) {

                }
            });
        }
    }

    //设置答题选项UI
    private void updateAnswerSelect(int index, int type, boolean isMy){
        switch (index){
            case 0:
                if (type == 1){
                    pk_first_select_answer.setBackgroundColor(Color.parseColor("#48CFAD"));
                    if (isMy == true){
                        pk_first_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_first_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }else if(type == 2){
                    pk_first_select_answer.setBackgroundColor(Color.parseColor("#AA1923"));
                    if (isMy == true){
                        pk_first_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_first_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 1:
                if (type == 1){
                    pk_second_select_answer.setBackgroundColor(Color.parseColor("#48CFAD"));
                    if (isMy == true){
                        pk_second_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_second_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }else if(type == 2){
                    pk_second_select_answer.setBackgroundColor(Color.parseColor("#AA1923"));
                    if (isMy == true){
                        pk_second_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_second_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 2:
                if (type == 1){
                    pk_third_select_answer.setBackgroundColor(Color.parseColor("#48CFAD"));
                    if (isMy == true){
                        pk_third_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_third_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }else if(type == 2){
                    pk_third_select_answer.setBackgroundColor(Color.parseColor("#AA1923"));
                    if (isMy == true){
                        pk_third_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_third_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 3:
                if (type == 1){
                    pk_fourth_select_answer.setBackgroundColor(Color.parseColor("#48CFAD"));
                    if (isMy == true){
                        pk_fourth_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_fourth_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }else if(type == 2){
                    pk_fourth_select_answer.setBackgroundColor(Color.parseColor("#AA1923"));
                    if (isMy == true){
                        pk_fourth_select_answer_bg.setVisibility(View.INVISIBLE);
                    }else {
                        pk_fourth_select_answer_bg.setVisibility(View.VISIBLE);
                    }
                }
                break;
        }
    }

    //更新分数进度
    private void updateScoreProgress(boolean isLeft){
        if (isLeft == true){
            pk_left_score.setText(pkAnswerModel.getMyScore()+"");
            pk_left_score_progress.setProgress(pkAnswerModel.getMyScore());
        }else{
            pk_right_score.setText(pkAnswerModel.getAnotherScore()+"");
            pk_right_score_progress.setProgress(pkAnswerModel.getAnotherScore());
        }
    }

    //根据答题时间计算分数
    private int getScore(int time, int index){
        int score = Integer.valueOf(pkAnswerModel.scoreArray.get(index));
        if (time >= pkRuleModel.getPkfullscoretime()){

        }else if (time >= pkRuleModel.getPkanswertime()/2){
            score *= 0.8;
        }else {
            score *= 0.5;
        }
        return score;
    }

    //答题时间
    private void answerTime(int time){
        Log.e("TAG","time="+time);

        if (time == 0){
            Log.e("TAG","本地答题超时~");
            //本地答题超时
            if (pkAnswerModel.getMySubjectIndex() < pkAnswerModel.getSubjectIndex()){
                if (pkAnswerModel.getMySelectIndex() == 0){
                    onClickSelect(pk_first_select_answer);
                }else if (pkAnswerModel.getMySelectIndex() == 1){
                    onClickSelect(pk_second_select_answer);
                }else if (pkAnswerModel.getMySelectIndex() == 2){
                    onClickSelect(pk_third_select_answer);
                }else if (pkAnswerModel.getMySelectIndex() == 3){
                    onClickSelect(pk_fourth_select_answer);
                }
            }

            if (anotherPKUserModel != null){
                if (pkAnswerModel.getMySubjectIndex() >= subjectList.size()){
                    stopTime();
                    return;
                }
                if (pkAnswerModel.getAnotherSubjectIndex() != pkAnswerModel.getSubjectIndex()){
                    pkAnswerModel.setAnswerTimeOut(true);
                    pkAnswerModel.setAnswerTimeOut(5);
                    startTime();
                }
            }

        }

        if (anotherPKUserModel == null){
            //机器人做答
            if (pkAnswerModel.getAnotherSubjectIndex() >= pkAnswerModel.getSubjectIndex()){
                return;
            }
            if (pkAnswerModel.isNewSubject() == false){
                return;
            }
            if (pkAnswerModel.getAnotherSubjectIndex() >= subjectList.size()){
                //答题完成了
                return;
            }
            if (time <= weakpkaModel.getTime()){
                //可以答题
                pkAnswerModel.setNewSubject(false);
                PKSubjectModel pkSubjectModel = subjectList.get(pkAnswerModel.getAnotherSubjectIndex());
                int tag = pkAnswerModel.answerArray.indexOf(pkSubjectModel.getAnswer());
                if (weakpkaModel.isStatus() == true){
                    pkAnswerModel.setAnotherSelectIndex(tag);
                    int score = getScore(time,pkAnswerModel.getAnotherSubjectIndex());
                    pkAnswerModel.setAnotherScore(pkAnswerModel.getAnotherScore()+score);
                    pkAnswerModel.setAnohterLinkCorrectCount(pkAnswerModel.getAnohterLinkCorrectCount()+1);
                    updateScoreProgress(false);
                    if (pkAnswerModel.getAnohterLinkCorrectCount() > pkAnswerModel.getAnohterMaxLinkCorrectCount()){
                        pkAnswerModel.setAnohterLinkCorrectCount(pkAnswerModel.getAnohterMaxLinkCorrectCount());
                    }
                }else {
                    if (pkAnswerModel.getAnohterLinkCorrectCount() > pkAnswerModel.getAnohterMaxLinkCorrectCount()){
                        pkAnswerModel.setAnohterMaxLinkCorrectCount(pkAnswerModel.getAnohterLinkCorrectCount());
                    }
                    pkAnswerModel.setAnohterLinkCorrectCount(0);
                    int x = (int) (Math.random() * pkSubjectModel.getSelectCount());
                    while (x == tag){
                        x = (int) (Math.random() * pkSubjectModel.getSelectCount());
                    }
                    pkAnswerModel.setAnotherSelectIndex(x);
                }
                pkAnswerModel.setAnotherSubjectIndex(pkAnswerModel.getSubjectIndex());
                showCorrectAnswer();

            }
        }

    }

    //展示答案
    private void answer(String answer, int time){
        if (pkAnswerModel.getAnotherSubjectIndex() >= pkAnswerModel.getSubjectIndex()){
            return;
        }
        if (pkAnswerModel.isNewSubject() == false){
            return;
        }
        if (pkAnswerModel.getAnotherSubjectIndex() >= subjectList.size()){
            //答题完成了
            return;
        }
        pkAnswerModel.setNewSubject(false);
        PKSubjectModel pkSubjectModel = subjectList.get(pkAnswerModel.getAnotherSubjectIndex());
        int tag = pkAnswerModel.answerArray.indexOf(pkSubjectModel.getAnswer());
        int selectTag = pkAnswerModel.answerArray.indexOf(answer);
        if (tag == selectTag){
            //回答正确
            pkAnswerModel.setAnotherSelectIndex(tag);
            int score = getScore(time,pkAnswerModel.getAnotherSubjectIndex());
            pkAnswerModel.setAnotherScore(pkAnswerModel.getAnotherScore()+score);
            pkAnswerModel.setAnohterLinkCorrectCount(pkAnswerModel.getAnohterLinkCorrectCount()+1);
            updateScoreProgress(false);
            if (pkAnswerModel.getAnohterLinkCorrectCount() > pkAnswerModel.getAnohterMaxLinkCorrectCount()){
                pkAnswerModel.setAnohterMaxLinkCorrectCount(pkAnswerModel.getAnohterLinkCorrectCount());
            }
        }else {
            //回答错误
            if (pkAnswerModel.getAnohterLinkCorrectCount() > pkAnswerModel.getAnohterMaxLinkCorrectCount()){
                pkAnswerModel.setAnohterMaxLinkCorrectCount(pkAnswerModel.getAnohterLinkCorrectCount());
            }
            pkAnswerModel.setAnohterLinkCorrectCount(0);
            pkAnswerModel.setAnotherSelectIndex(selectTag);
        }
        pkAnswerModel.setAnotherSubjectIndex(pkAnswerModel.getSubjectIndex());
        showCorrectAnswer();
    }

    //两个答题完了再更新对方答案，正确答案
    private void showCorrectAnswer(){
        if (pkAnswerModel.getMySubjectIndex() != pkAnswerModel.getAnotherSubjectIndex()){
            return;
        }
        PKSubjectModel pkSubjectModel = subjectList.get(pkAnswerModel.getMySubjectIndex()-1);
        int tag = pkAnswerModel.answerArray.indexOf(pkSubjectModel.getAnswer());
        if (pkAnswerModel.getMySelectIndex() == tag && pkAnswerModel.getAnotherSelectIndex() == tag){
            //两个都回答正确
            updateAnswerSelect(tag,1,false);
        }else if (pkAnswerModel.getMySelectIndex() == tag){
            updateAnswerSelect(pkAnswerModel.getAnotherSelectIndex(),2,true);
        }else if (pkAnswerModel.getAnotherSelectIndex() == tag){
            updateAnswerSelect(tag,1,false);
        }else {//两个都答错
            if (pkAnswerModel.getMySelectIndex() == pkAnswerModel.getAnotherSelectIndex()){
                updateAnswerSelect(pkAnswerModel.getMySelectIndex(),2,false);
            }else {
                updateAnswerSelect(pkAnswerModel.getAnotherSelectIndex(),2,true);
            }
            updateAnswerSelect(tag,1,true);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                updateData();
            }
        },pkRuleModel.getPkshowanswertime()*1000);
    }

    //网络状态
    @Override
    public void onNetChange(int netMobile) {
        super.onNetChange(netMobile);
        Log.e("TAG","网络状态："+netMobile);
        if (netMobile == -1){
            //没有网络
            progressBar.stop();
            back("亲，关键时刻断网啦~","0",false);
        }
    }

    //上传结果
    private void updatePKResult(){
        Log.e("TAG","上传结果1");
        if (pkRoomModel.getSendUserid().equals(CustomApplication.loginModel.getUid())==false){//统一由发起者上传对战结果
            return;
        }
        Log.e("TAG","上传结果2");
        int wintype = 0;
        if (pkAnswerModel.getMyScore() > pkAnswerModel.getAnotherScore()){
            if (pkRoomModel.getSendUserid().equals(CustomApplication.loginModel.getUid())){
                wintype = 1;
            }else {
                wintype = 2;
            }
        }else if (pkAnswerModel.getMyScore() < pkAnswerModel.getAnotherScore()){
            String userid = "";
            if (anotherPKUserModel != null){
                userid = anotherPKUserModel.getUserid();
            }else {
                userid = roleUserModel.getUserid();
            }
            if (pkRoomModel.getSendUserid().equals(userid)){
                wintype = 1;
            }else {
                wintype = 2;
            }
        }
        if ( pkAnswerModel.getMyScore() == 0 && pkAnswerModel.getMyScore() == pkAnswerModel.getAnotherScore()){
            wintype = 3;
        }
        String url = "miniapp/pkappid/pkresult.do";
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.typeKey,pkRoomModel.getPkType()+"");
        map.put(APIKey.idKey,pkRoomModel.getId()+"");
        map.put("wintype",wintype+"");
        Log.e("TAG","上传结果3:"+map);
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","上传结果:"+data);
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    stopTime();
                    pkResultModel = GsonTools.getPKResultModel(data);
                    acceptPKResultUserInfo = GsonTools.getacceptuserpkinfo(data);
                    sendPKResultUserInfo = GsonTools.getsenduserpkinfo(data);

                    pkMsgModel.setName(PKMsgModel.PKResult);
                    pkMsgModel.setSenduserid(sendPKResultUserInfo.getUserid());


                    if (sendPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
                        pkMsgModel.setSendscore(pkAnswerModel.getMyScore());
                        pkMsgModel.setSendlinkcorrect(pkAnswerModel.getMyLinkCorrectCount());
                    }else {
                        pkMsgModel.setSendscore(pkAnswerModel.getAnotherScore());
                        pkMsgModel.setSendlinkcorrect(pkAnswerModel.getAnohterLinkCorrectCount());
                    }
                    pkMsgModel.setSendwinlinkcount(sendPKResultUserInfo.getWinLinkcount());
                    pkMsgModel.setAddplaylevelsend(pkResultModel.getAddplaylevelsend());
                    pkMsgModel.setAddgoldcountsend(pkResultModel.getAddgoldcountsend());

                    pkMsgModel.setAcceptuserid(acceptPKResultUserInfo.getUserid());
                    if (acceptPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
                        pkMsgModel.setAcceptscore(pkAnswerModel.getMyScore());
                        pkMsgModel.setAcceptlinkcorrect(pkAnswerModel.getMyLinkCorrectCount());
                    }else {
                        pkMsgModel.setAcceptscore(pkAnswerModel.getAnotherScore());
                        pkMsgModel.setAcceptlinkcorrect(pkAnswerModel.getAnohterLinkCorrectCount());
                    }
                    pkMsgModel.setAcceptwinlinkcount(acceptPKResultUserInfo.getWinLinkcount());
                    pkMsgModel.setAddplaylevelaccept(pkResultModel.getAddplaylevelaccept());
                    pkMsgModel.setAddgoldcountaccept(pkResultModel.getAddgoldcountaccept());
                    sendPKMsg();

                    Intent intent = new Intent(PKActivity.this, EndPKActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("pkuser",pkUserModel);
                    bundle.putSerializable("pkanswer", pkAnswerModel);//序列化
                    if (anotherPKUserModel == null){
                        bundle.putSerializable("roleuser",roleUserModel);
                    }else {
                        bundle.putSerializable("anotherpkuser",anotherPKUserModel);
                    }
                    bundle.putSerializable("pkresult",pkResultModel);
                    bundle.putSerializable("acceptpkresultuserinfo",acceptPKResultUserInfo);
                    bundle.putSerializable("sendpkresultuserinfo",sendPKResultUserInfo);
                    intent.putExtras(bundle);//发送数据
                    startActivity(intent);
                    progressBar.stop();
                    finish();
                }
            }

            @Override
            public void onError(String msg) {
                Log.e("TAG","上传结果:"+msg);
            }
        });

    }
}
